import { useEffect, useState } from "react";

function CountInterval()
{
    const [count,SetCount] = useState(0);

    useEffect(() => {
        console.log(123);
        const intervalId = setInterval(() => {
            console.log('更新count...');
            SetCount(c => c + 1); // 你想要每秒递增该计数器...
        }, 1000)
        return () => {
            console.log('卸载');
            clearInterval(intervalId);
        }
    }, []);

    return <h1>{count}</h1>
}

export default function Demo5()
{
    const [count,SetCount] = useState(0);
    const [list,SetList] = useState([]);
    const [num,SetNum] = useState(0);
    const [show,SetShow] = useState(false);


    const OnDel = () =>
    {

    }

    const GetListData = () =>
    {
        const data = [
            {
                id:1,
                name:'demo'
            },
            {
                id:2,
                name:'test'
            },
            {
                id:3,
                name:'admin'
            }
        ];

        if(data.length > 0)
        {
            SetList([...data]);
        }
    }

    // 更新
    // useEffect(() =>
    // {
    //     GetListData();
    // });

    // 挂载
    useEffect(() =>
    {
        GetListData();
    },[]);

    useEffect(() =>
    {
        console.log('根据count发请求');
    },[num]);

    

    return (
        <>
            { count }

            <br />

            <button onClick={() => SetCount(count + 1)}>count + 1</button>
            <button onClick={() => SetNum(num + 1)}>num + 1</button>

            <hr />

            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Operate</th>
                    </tr>
                </thead>
                <tbody>
                    {list.map(item =>
                    {
                        return (
                            <tr key={item.id}>
                                <td>{ item.id }</td>
                                <td>{ item.name }</td>
                                <td>
                                    <button>编辑</button>
                                    <button onClick={() => OnDel(item.id)}>删除</button>
                                </td>
                            </tr>
                        )
                    })}
                </tbody>
            </table>

            <hr />

            {show && <CountInterval />}

            <br />

            <button onClick={() => SetShow(!show)}> { show ? '隐藏' : '显示' } </button>
        </>
    )
}